//
//  WFComposeTV.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/18.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit

class WFComposeTV: UITextView {
    
    // MARK:  - 懒加载控件
    private lazy var placeHolderLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "老夫聊发少年狂"
        //多行显示
        label.numberOfLines = 0
        label.textColor = UIColor.lightGrayColor()
        
        return label
    }()
    
    //  占位文字
    //  给xib添加设置属性
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
        
    }
    
    //重写font
    override var font: UIFont? {
        didSet {
            // 如果外界传入nil直接返回
            if font == nil {
                return
            }
            placeHolderLabel.font = font
        }
    }
    
    //  重写text
    override var text: String? {
        
        didSet {
            placeHolderLabel.hidden = hasText()
            
        }
    }


    // MARK:  - 重写构造
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setUpUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUpUI()
    }
    
    //添加控件设置约束
    private func setUpUI(){
        //  监听UITextView文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        addSubview(placeHolderLabel)
        
        //进行手写布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
        
    }
    
    // MARK:  - 监听文字改变的方法
    @objc private func textChange(){
        placeHolderLabel.hidden = self.hasText()
    }
    
    // MARK:  - 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

}
